<?php
class Virefyorderedit
{
    private $CI;
    //接收的信息
    private $orderId;
    private $editId;
    private $poundage;
    private $flag;
    private $note;
    //需要返回的参数
    public $NewOrderId = 0;//新生成的订单号
    public $orderEditBaseRow;//订单信息
    //需要用到的参数
    private $amountCarry = 0;
    private $amountBonus = 0;
    private $amountBack = 0;
    private $orderProfitData = array();//新拼装的分润信息
    
    public function __construct()
    {
        $this->CI = & get_instance();
        $this->CI->load->library('swiftpass/swiftpay', null, 'swiftpay');
        $this->CI->load->model('order_base_model', 'order_base');
        $this->CI->load->model('order_edit_model', 'order_edit');
        $this->CI->load->model('order_profit_model', 'order_profit');
        $this->CI->load->model('user_account_model', 'user_account');
        $this->CI->load->model('account_log_model', 'account_log');
        $this->CI->load->model('order_tb_model', 'order_tb');
        $this->CI->load->model('order_tb_detail_model', 'order_tb_detail');
        $this->CI->load->model('pay_record_model', 'pay_record');
        $this->CI->load->model('trade_refund_model', 'trade_refund');
        $this->CI->load->model('user_transfer_charge_model', 'user_transfer_charge');
    }
    
    /**
     * 初始化
     * @param unknown $orderId 订单id
     * @param unknown $editId 订单修改id
     * @param unknown $poundage 手续费
     * @param unknown $flag 审核状态
     * @param unknown $note 备注
     */
    public function initialize($orderId, $editId, $poundage, $flag, $note)
    {
        $this->orderId = $orderId;
        $this->editId  = $editId;
        $this->poundage = $poundage;
        $this->flag = $flag;
        $this->note = $note;
    }
    
    /**
     * 同意退款
     */
    public function auditSuccess()
    {
        //查询订单信息
        $orderEditBaseRow = $this->getOrderEditBaseInfo();
        $this->orderEditBaseRow = $orderEditBaseRow;
        
        if($orderEditBaseRow->flag != 1)
            return array('error_code'=>31203,'error_msg'=>'订单'.$this->orderId.'已审核');
        if($orderEditBaseRow->bit_pay < 0)
            return array('error_code'=>31204,'error_msg'=>'订单'.$this->orderId.'未支付');
        if($orderEditBaseRow->bit_use > 0)
            return array('error_code'=>31205,'error_msg'=>'订单'.$this->orderId.'已使用');

        $bit_wan = $orderEditBaseRow->bit_wan;
        $o_num = $orderEditBaseRow->o_num;
        $n_num = $orderEditBaseRow->n_num;
        $o_amount_fee = $orderEditBaseRow->o_amount_fee;
        $orderEditBaseRow->mid = 2;//2表示"服务器传送数据到终端"
        $orderEditBaseRow->old_order_id = $orderEditBaseRow->order_id;
        $orderEditBaseRow->bit_opt = $orderEditBaseRow->bit_opt - 128;//128表示"退票操作"
        //$orderEditBaseRow->amount_total_n = $orderEditBaseRow->amount_total/$o_num*$n_num;
        //$orderEditBaseRow->amount_fee_n = $orderEditBaseRow->amount_fee/$o_num*$n_num;
        $orderEditBaseRow->amount_total_n = $this->AddSubtractMultiplyDivideCalculation('old', $orderEditBaseRow->amount_total, $o_num, $n_num);
        $orderEditBaseRow->amount_fee_n = $this->AddSubtractMultiplyDivideCalculation('old', $orderEditBaseRow->amount_fee, $o_num, $n_num);
        $orderEditBaseRow->plantime = $orderEditBaseRow->tplantime;
        $orderEditBaseRow->sfz = $orderEditBaseRow->tsfz;
        //如果是淘宝订单
        if($bit_wan&2048)
            $orderEditBaseRow->end_time = $orderEditBaseRow->tplantime;
        
        //获取账户余额信息
        //$amount_carry = $orderEditBaseRow->amount_fee/$o_num*($o_num-$n_num);
        $amount_carry = $this->AddSubtractMultiplyDivideCalculation('new', $orderEditBaseRow->amount_fee, $o_num, $n_num);
        $this->amountCarry = $amount_carry-$amount_carry*$this->poundage/100;//手续费
        //获取退款金额
        //$amount_back = $o_amount_fee/$o_num*($o_num-$n_num);
        $amount_back = $this->AddSubtractMultiplyDivideCalculation('new', $o_amount_fee, $o_num, $n_num);
        $this->amountBack = $amount_back-$amount_back*$this->poundage/100;

        // 兴业银行支付 原路返回
        if ($this->checkNeedRefundChannel()) {
            return $this->refundChannel($orderEditBaseRow);
        } else {
            //获得订单分润信息
            $this->getOrderProfitInfo($o_num,$n_num);
            //对数据表进行增删改操作
            $this->addUpdateDeleteData($orderEditBaseRow);
        }
    }

    public function checkNeedRefundChannel()
    {
        // 判断是否扫码购 是否兴业银行支付
        if ($this->orderEditBaseRow->calculate_method == 3 && $this->orderEditBaseRow->pay_method == 188) {
            return true;
        }
        return false;
    }

    /**
     * 第三方退款通道 原路返回
     */
    public function refundChannel($orderEditBaseRow)
    {
        $payRecord = $this->CI->pay_record->findByPayId($orderEditBaseRow->pay_id);
        if ($payRecord->num_rows() == 0) {
            return array('error_code'=>31207,'error_msg'=>'订单支付记录不存在');
        }
        $payRecord = $payRecord->row();
        if ($payRecord->pay_method != 188) {
            return array('error_code'=>31208,'error_msg'=>'订单与支付记录的支付方式不符');
        }

        $this->CI->db->trans_start();

        $tradeRefund = array(
            'pay_id' => $payRecord->pay_id,
            'transaction_id' => empty($payRecord->serial_number) ? 0 : $payRecord->serial_number,
            'refund_id' => $this->editId,
            'total_fee' => $payRecord->amount,
            'refund_fee' => $this->amountBack,
            'sid'       => $orderEditBaseRow->sid
        );

        // 插入交易退款信息
        $refundId = $this->CI->trade_refund->insert($tradeRefund);
        //添加新的订单信息
        $orderEditBaseRow->plantime = $orderEditBaseRow->tplantime;
        $orderEditBaseRow->sfz = $orderEditBaseRow->tsfz;
        $this->NewOrderId = $this->CI->order_base->add($orderEditBaseRow);

        //删除原本的订单信息
        $this->CI->order_base->delete($this->orderId);
        //修改订单修改表的订单信息
        $this->CI->order_edit->update(array('edit_id'=>$this->editId, 'order_id'=>$this->orderId, 'flag'=>$this->flag, 'note'=>$this->note,'n_order_id'=>$this->NewOrderId, 'poundage'=>$this->poundage, 'amount_back'=>$this->amountBack));

        $this->CI->db->trans_complete();

        if ($this->CI->db->trans_status() === FALSE) {
            return array('error_code'=>31206,'error_msg'=>'订单'.$this->orderId.'修改失败');
        }

        //查找支付通的商户号 和秘钥
        $swiftParam = $this->CI->user_transfer_charge->findBySid($orderEditBaseRow->sid);
        if ($swiftParam->num_rows() == 0) {
            return array('error_code'=>31206,'error_msg'=> '编号('.$orderEditBaseRow->sid.')的景区未绑定银扫码参数');
        }
        $swiftParam = $swiftParam->row();

        $request = array(
            'service'        => 'unified.trade.refund',
            'out_trade_no'   => $payRecord->pay_id,
            'transaction_id' => empty($payRecord->serial_number) ? 0 : $payRecord->serial_number,
            'out_refund_no'  => $this->editId,
            'total_fee'      => $payRecord->amount * 100,
            'refund_fee'     => $this->amountBack * 100,
            'mch_id'         => $swiftParam->mch_id,
            'op_user_id'     => $swiftParam->mch_id,
            'refund_channel' => 'ORIGINAL'
        );
        $response = $this->CI->swiftpay->submit($request, $swiftParam->key);
        $data['message'] = '';
        if ($response) {
            $data['status'] = 1; //退款成功
        } else {
            $data['status'] = 2; //退款失败
            $data['message'] = $this->CI->swiftpay->getError();
        }
        $this->CI->trade_refund->updatePartById($refundId, $data);

        return array('error_code'=>0);
    }
    
    /**
     * 拒绝退款
     */
    public function auditFail()
    {
        //查询订单信息
        $orderEditBaseRow = $this->getOrderEditBaseInfo();
        $this->orderEditBaseRow = $orderEditBaseRow;
        
        $this->CI->db->trans_start();
        //修改订单修改表的订单信息
        $this->CI->order_edit->update(array('edit_id'=>$this->editId, 'order_id'=>$this->orderId, 'flag'=>$this->flag, 'note'=>$this->note, 'poundage'=>$this->poundage, 'amount_back'=>$this->amountBack));
        //修改订单表信息(128表示退款操作)
        $this->CI->order_base->update_set(array('order_id'=>$this->orderId),array('bit_opt'=>128));
        $this->CI->db->trans_complete();
        
        if ($this->CI->db->trans_status() === FALSE) {
            return array('error_code'=>31206,'error_msg'=>'订单'.$this->orderId.'修改失败');
        }
        
        return array('error_code'=>0);
    } 
    
    /**
     * 获得订单信息
     */
    private function getOrderEditBaseInfo()
    {
        $orderEditBaseWhere = array('order_id'=>$this->orderId,'edit_id'=>$this->editId);
        $orderEditBaseSelect = 'ob.*,oe.edit_id,oe.sfz as tsfz,oe.plantime as tplantime,oe.n_num,oe.o_num,oe.flag,oe.o_amount_fee';
        $orderEditBaseQuery = $this->CI->order_edit->select_order_edit_base_info($orderEditBaseWhere,$orderEditBaseSelect);
        if($orderEditBaseQuery->num_rows() <= 0) {
            return array('error_code'=>31201,'error_msg'=>'订单'.$this->orderId.'信息不存在');
        }
        $orderEditBaseRow = $orderEditBaseQuery->row();
        
        return $orderEditBaseRow;
    }
        
    /**
     * 获得订单分润信息
     * @param unknown $o_num 原有订单数量
     * @param unknown $n_num 现有订单数量
     */
    private function getOrderProfitInfo($o_num,$n_num)
    {
        $orderProfitQuery = $this->CI->order_profit->findById($this->orderId);
        if($orderProfitQuery->num_rows() <= 0) {
            return array('error_code'=>31202,'error_msg'=>'订单'.$this->orderId.'没有分润信息');
        }
        $orderProfitRow = $orderProfitQuery->result_array();
        
        foreach($orderProfitRow as $key => $value)
        {
            //$amount = $value['amount']/$o_num*$n_num;
            $amount = $this->AddSubtractMultiplyDivideCalculation('old', $value['amount'], $o_num, $n_num);
            $value['amount'] = $amount;
            $this->orderProfitData[$key] = $value;
            if($value['bit_trade'] == 134217728){//UB使用多少，退UB
                //$this->amountBonus += $value['amount']/$o_num*($o_num-$n_num);
                $this->amountBonus += $this->AddSubtractMultiplyDivideCalculation('new', $value['amount'], $o_num, $n_num);
            }
        }
    }
    
    /**
     * 对数据表进行增删改操作
     * @param unknown $orderEditBaseRow 订单表信息
     */
    private function addUpdateDeleteData($orderEditBaseRow)
    {
        $this->CI->db->trans_start();
        
        //添加新的订单信息
        $this->NewOrderId = $this->CI->order_base->add($orderEditBaseRow);
        foreach ($this->orderProfitData as $key=>$value){
            $this->orderProfitData[$key]['order_id'] = $this->NewOrderId;
        }
        //添加删除订单分润信息
        $this->CI->order_profit->addBatch($this->orderProfitData);
        $this->CI->order_profit->delete($this->orderId);
        //删除原本的订单信息
        $this->CI->order_base->delete($this->orderId);
        //修改订单修改表的订单信息
        $this->CI->order_edit->update(array('edit_id'=>$this->editId, 'order_id'=>$this->orderId, 'flag'=>$this->flag, 'n_order_id'=>$this->NewOrderId, 'poundage'=>$this->poundage, 'amount_back'=>$this->amountBack));
        //修改账户余额信息.修改订单操作不用修改账户余额
        //$this->CI->user_account->updateAddAmount(array('uid'=>$orderEditBaseRow->payer_uid,'amount_carry'=>$this->amountCarry, 'amount_bonus'=>$this->amountBonus));
        //添加账户余额日志信息.修改订单操作不用添加日志记录
        //$this->addTableAccountLog($orderEditBaseRow->payer_uid);
        //如果订单是淘宝订单
        if($orderEditBaseRow->bit_wan & 2048){
            $this->updateTaobao($orderEditBaseRow->other_id,$orderEditBaseRow->n_num,$orderEditBaseRow->tsfz);
        }
        $this->CI->db->trans_complete();
        
        if ($this->CI->db->trans_status() === FALSE) {
            return array('error_code'=>31206,'error_msg'=>'订单'.$this->orderId.'修改失败');
        }
        
        return array('error_code'=>0);
    }
    
    /**
     * 添加账户余额日志信息
     */
    private function addTableAccountLog($payer_uid){
        $accountLog = array(
            'uid' => $payer_uid,
            'amount' => $this->amountCarry,
            'type' => 8,//8表示"退票CANCEL"
            'account_type' => 1,//1表示"可提现"
            'product_type' => 'scenic',
            'order_id' => $this->NewOrderId
        );
        $this->CI->account_log->insertAccountLog($accountLog);
    }
    
    /**
     * 更新淘宝信息
     */
    private function updateTaobao($other_id,$n_num,$sfz){
        $this->CI->order_tb->update(array('sfz'=>$sfz,'other_id'=>$other_id));
        $order_tb_n = array(
            'other_id' => $other_id,
            'left_num' => 0,
            'use_num' => $n_num,
            'order_id' => $this->NewOrderId,
            'serial_num' => md5($this->NewOrderId)
        );
        $this->CI->order_tb_detail->update($order_tb_n,$this->orderId);
    }
    
    /**
     * 加减乘除计算
     */
    private function AddSubtractMultiplyDivideCalculation($oldOrNew, $amount, $oldNum, $newNum)
    {
        $calculationResult = 0;
        switch ($oldOrNew) {
            case 'old':
                $bcdivResult = bcdiv($amount, $oldNum, 2);//先除
                $bcmulResult = bcmul($bcdivResult, $newNum, 2);//后乘
                $calculationResult = $bcmulResult;
                break;
            case 'new':
                $surplusNum = $oldNum - $newNum;//剩余数量
                $bcdivResult = bcdiv($amount, $oldNum, 2);//先除
                $bcmulResult = bcmul($bcdivResult, $surplusNum, 2);//后乘
                $calculationResult = $bcmulResult;
                break;
        }
         
        return $calculationResult;
    }
}


